<template>
  <div class="work_list_receive">
    <one-title :title="titleText" @refreshData="refresh">
      <div class="mes_btn">
        <div class="down_btn">
          <span v-btn-permission="'downTemplate'" class="download_btn" @click="downTemplate">导入模板下载</span>
          <router-link v-btn-permission="'importHistory'" :to="{path: 'importHistory'}" class="see_history">已导入历史记录</router-link>
        </div>
        <!--<el-button disabled>-->
          <!--<i class="iconfont icon-tongbu"></i>-->
          <!--同步工艺-->
        <!--</el-button>-->
        <!--<el-button disabled>-->
          <!--<i class="iconfont icon-btn_receive"></i>-->
          <!--同步任务-->
        <!--</el-button>-->
        <disabled-btn :judge="deleteWorkJudge"
                      v-btn-permission="'del'"
                      iconClass="iconfont icon-btn_delete"
                      btnText="删除"
                      @judgeClick="deleteWork"></disabled-btn>
        <disabled-btn :judge="editWorkJudge"
                      v-btn-permission="'edit'"
                      iconClass="iconfont icon-btn_edit"
                      btnText="修改"
                      @judgeClick="editWork()"></disabled-btn>
        <!--<disabled-btn :judge="returnWorkJudge"-->
                      <!--iconClass="iconfont icon-btn_return"-->
                      <!--btnText="退回"-->
                      <!--@judgeClick="returnWork"></disabled-btn>-->
        <disabled-btn :judge="recoveryWorkJudge"
                      v-btn-permission="'recovery'"
                      iconClass="iconfont icon-btn_recovery"
                      btnText="恢复"
                      @judgeClick="recoveryWork"></disabled-btn>
        <disabled-btn :judge="terminatedWorkJudge"
                      v-btn-permission="'terminated'"
                      iconClass="iconfont icon-btn_abend"
                      btnText="终止"
                      @judgeClick="terminatedWork"></disabled-btn>
        <disabled-btn :judge="pausedWorkJudge"
                      v-btn-permission="'paused'"
                      iconClass="iconfont icon-zanting"
                      btnText="暂停"
                      @judgeClick="pausedWork"></disabled-btn>
        <disabled-btn :judge="lowerHairJudge"
                      v-btn-permission="'lowerHair'"
                      iconClass="iconfont icon-btn_issued"
                      btnType="primary"
                      btnText="下发"
                      @judgeClick="lowerHair"></disabled-btn>
        <!--<el-button type="primary" @click="_export">-->
        <!--<i class="iconfont icon-btn_receive"></i>-->
        <!--导出-->
        <!--</el-button>-->
        <el-button v-btn-permission="'showImport'" type="success" @click="showImport">
          <i class="iconfont icon-btn_import"></i>
          导入
        </el-button>
      </div>
    </one-title>
    <div class="task_tree_container">
      <task-bom-tree
        ref="taskBomTree"
        @selectNode="_selectNode"
      ></task-bom-tree>
      <div class="task_tree_content">
        <mes-search-comp
          ref="mesSearch"
          :searchList="tableColConfig"
          :searchResult="searchResult"
          :showSlotSet="true"
          :showSlotExport="true"
          @setCol="$refs.ColumnControl.openDialog()"
          @exportTable="_exportTable"
          @searchInfo="_info">
        </mes-search-comp>
        <!--任务信息-->
        <div class="task_info_cont" v-show="Object.keys(taskInfoDetail).length">
          <info-grid
            :rowSize="5"
            labelWidth="110px"
            :infoData="taskInfoDetail"
            :items="taskInfoConfig"></info-grid>
        </div>
        <div class="table_container">
          <el-table
            border
            stripe
            :data="listData.list"
            v-loading="isLoading"
            style="width: 100%"
            ref="mesTable"
            :max-height="tableMaxHeight"
            :row-class-name="({row}) => !selectData.some((item) => item.id === row.id) || 'line_selected'"
            @row-click="row => $refs.mesTable.toggleRowSelection(row)"
            @sort-change="_sort"
            @selection-change="handleSelectionChange"
            @filter-change="handleFilterChange">
            <el-table-column
              type="selection"
              fixed="left"
              width="40">
            </el-table-column>
            <mes-col-comp
              :key="column.prop"
              v-for="column in columnList"
              @jump="(row) => editWork(row)"
              :column="column"></mes-col-comp>
            <el-table-column
              align="center"
              label="操作"
              min-width="160"
              fixed="right"
              :resizable="false"
              class-name="operation_btn"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span class="jump_item"
                      @click.stop="$router.push({path: 'workListInfoDetail', query: {id: scope.row.id}})">
                  信息总览
                </span>
                <span class="jump_item" @click.stop="showLog(scope.row)">操作记录</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <mes-pagination
          @updateData="init"
          :currentPage="listData.pageNo"
          :total="listData.count || 0"
          :pageSize="listData.pageSize">
        </mes-pagination>
      </div>
    </div>
    <!--工单导入-->
    <import-step ref="importStep"></import-step>
    <!--暂停，恢复，终止-->
    <work-order-batch
      ref="WorkOrderBatch"
      @showLog="filterlog"
      @submitBatch="_submitBatch">
    </work-order-batch>
    <!-- 日志详情 -->
    <log-detail ref="logDetail"></log-detail>
    <!--下载导入模板-->
    <!--<down-template ref="downTemplate"></down-template>-->
    <!--列隐藏-->
    <column-control
      ref="ColumnControl"
      :colList="tableColConfig"
      @saveCol="saveCol"
    ></column-control>
  </div>
</template>

<script>
import ImportStep from './components/ImportStep'
import WorkOrderBatch from './components/WorkOrderBatch'
// import DownTemplate from './components/downTemplate'
// 工单列配置
import receiveColumn from './components/receiveColumn'
// 任务号信息配置
import taskInfoConfig from './components/taskInfoConfig'

/* 工单状态 */
// 正常
const NORMAL = 'Normal'
// 已暂停
const PAUSED = 'Paused'
// 已终止
const TERMINATED = 'Terminated'

/* 工单进度 */
// 待下发
const TOBEASSIGNED = 'ToBeAssigned'
// 待确认
// const TOBECONFIRMED = 'ToBeConfirmed'
// 待拆分
// const TOBESPLITTED = 'ToBeSplitted'
// 部分拆分
// const PARTSPLITTED = 'PartSplitted'
// 拆分完成
// const COMPLETESPLITTED = 'CompleteSplitted'
// 已完成
const FINISHED = 'Finished'

export default {
  name: 'WorkListReceive',
  data() {
    return {
      titleText: '工单管理', // 模块标题
      tableColConfig: receiveColumn, // 工单列配置
      taskInfoConfig: taskInfoConfig, // 任务号信息配置
      taskInfoDetail: {},
      workorderIds: [], // 工单ID数组
      isLoading: true, // 数据加载中
      selectData: [], // 当前选中的工单
      searchData: {}, // 搜索的字段
      searchResult: NaN, // 搜索结果数
      sortData: {}, // 排序的字段
      taskNumber: '', // 任务树ID
      checkedKeys: window.localStorage.getItem(this.$route.name), // 显示的列集合
    }
  },
  computed: {
    // 列表数据
    listData() {
      return this.$store.state.workListReceive.listData
    },
    // 列循环
    columnList() {
      this.$nextTick(() => {
        this.$refs.mesTable.doLayout()
      })
      let checkedKeysList = this.checkedKeys ? JSON.parse(this.checkedKeys) : this.tableColConfig.reduce((pre, cur) => [...pre, cur.prop], [])
      return this.tableColConfig.filter(item => item.noForCol !== true && (item.noChecked === true || checkedKeysList.some(key => key === item.prop)))
    },
    // 验证是否已选
    _selected() {
      if (!this.selectData.length) return {msg: '请选择需要操作的工单！'}
    },
    // 验证是否单选
    singleElection() {
      if (this.selectData.length > 1) return {msg: '请选择一条工单进行操作！', disabled: true}
    },
    // 下发判断
    lowerHairJudge() {
      if (this._selected) return this._selected
      if (this.selectData.some(item => item.statusValue !== NORMAL || item.workorderProcessStatusValue !== TOBEASSIGNED)) {
        return {msg: '请选择工单状态为“正常”且进度状态为“待下发”的工单进行下发！', disabled: true}
      }
      return {msg: false}
    },
    // 回退判断
    returnWorkJudge() {
      if (this._selected) return this._selected
      if (this.selectData.some(item => item.statusValue !== NORMAL || item.workorderProcessStatusValue !== TOBEASSIGNED || item.sourceValue !== 'MES10')) {
        return {
          msg: '请选择工单状态为“正常”，工单进度为“待下发”，且工单来源为“MES10”的工单进行退回！',
          disabled: true
        }
      }
      return {msg: false}
    },
    // 删除判断
    deleteWorkJudge() {
      if (this._selected) return this._selected
      if (this.selectData.some(item => item.statusValue !== NORMAL || item.workorderProcessStatusValue !== TOBEASSIGNED || item.sourceValue !== 'Import')) {
        return {
          msg: '请选择工单状态为“正常”，工单进度为“待下发”，且工单来源为“导入”的工单进行删除！',
          disabled: true
        }
      }
      return {msg: false}
    },
    // 编辑判断
    editWorkJudge() {
      if (this._selected) return this._selected
      if (this.singleElection) return this.singleElection
      if (this.selectData[0].workorderProcessStatusValue === FINISHED) {
        return {
          msg: '请选择工单进度不是“已完成”的工单进行修改！',
          disabled: true
        }
      } else {
        return {msg: false}
      }
    },
    // 暂停判断
    pausedWorkJudge() {
      if (this._selected) return this._selected
      if (this.singleElection) return this.singleElection
      if (this.selectData[0].statusValue !== NORMAL || this.selectData[0].workorderProcessStatusValue === FINISHED) {
        return {
          msg: '请选择工单状态为“正常”，且工单进度不是“已完成”的工单进行暂停！',
          disabled: true
        }
      }
      return {msg: false}
    },
    // 恢复判断
    recoveryWorkJudge() {
      if (this._selected) return this._selected
      if (this.singleElection) return this.singleElection
      if (this.selectData[0].statusValue !== PAUSED) {
        return {
          msg: '请选择工单状态为“已暂停”的工单进行恢复！',
          disabled: true
        }
      }
      return {msg: false}
    },
    // 终止判断
    terminatedWorkJudge() {
      if (this._selected) return this._selected
      if (this.singleElection) return this.singleElection
      if (this.selectData[0].statusValue === TERMINATED || this.selectData[0].workorderProcessStatusValue === FINISHED) {
        return {
          msg: '请选择工单状态为“正常”或“已暂停”，且工单进度不是“已完成”的工单进行终止！',
          disabled: true
        }
      }
      return {msg: false}
    },
    // 同步工艺判断
    synchroProcessJudge() {
      if (this._selected) return this._selected
      if (this.singleElection) return this.singleElection
      if (this.selectData[0].statusValue !== NORMAL || this.selectData[0].statusValue !== PAUSED) {
        return {
          msg: '请选择工单状态为“正常”和“已暂停”的工单进行操作！',
          disabled: true
        }
      }
      return {msg: false}
    },
  },
  components: {
    ImportStep,
    WorkOrderBatch,
    // DownTemplate
  },
  mounted() {
    this.$refs.taskBomTree.init()
    this.init()
  },
  methods: {
    // 修改列显示
    saveCol(checkedKeys) {
      this.checkedKeys = checkedKeys
    },
    // 列筛选回调
    handleFilterChange(filters) {
      let query = this.$filterParams(this.tableColConfig, filters)
      Object.assign(this.searchData, query.search)
      this.$refs.mesTable.clearSort()
      this.sortData = query.order
      this.init()
    },
    // 修改工单进度状态
    changeStatus(obj) {
      let workorderIds = this.selectData.reduce((pre, cur) => [...pre, cur.id], [])
      let postData = {
        ...obj,
        workorderIds: workorderIds, // 工单id列表
      }
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/workorder/workorder/changestatus',
        data: postData,
        noCommit: true
      }).then(() => {
        this.$refs.WorkOrderBatch.batchDialog = false
        this.$message({
          type: 'success',
          message: obj.msg,
          duration: 1500,
          center: true
        })
        this.init()
      })
    },
    // 下发工单
    lowerHair() {
      this.mesConfirm('选中的工单将被下发, 是否继续?', '下发提示').then(() => {
        this.changeStatus({
          workorderActionId: 'ID_WAT_Assign',
          msg: '下发成功',
        })
      })
    },
    // 退回工单
    returnWork() {
      this.mesConfirm('选中的工单将被退回, 是否继续?', '退回提示').then(() => {
        this.changeStatus({
          workorderActionId: 'ID_WAT_Recall',
          msg: '退回成功',
        })
      })
    },
    // 删除工单
    deleteWork() {
      this.confirmDelete().then(() => {
        this.changeStatus({
          workorderActionId: 'ID_WAT_Delete',
          msg: '删除成功',
        })
      })
    },
    // 编辑工单
    editWork(data = null) {
      if (data && data.workorderProcessStatusValue === FINISHED) {
        // 工单编码点击判断
        this.$message({
          type: 'error',
          message: '请选择工单进度不是“已完成”的工单进行修改！',
          duration: 1500,
          center: true
        })
      } else {
        this.$router.push({
          name: 'workListReceiveDetail',
          params: {
            id: data ? data.id : this.selectData[0].id
          }
        })
      }
    },
    // 获取可暂停的批次
    pausedWork() {
      this.getPausedBatch(this.selectData[0], 'ID_WAT_Pause', 'getcanpausebatch')
    },
    // 获取可恢复的批次
    recoveryWork() {
      this.getPausedBatch(this.selectData[0], 'ID_WAT_Resume', 'getcanresumebatch')
    },
    // 获取可终止的批次
    terminatedWork() {
      this.getPausedBatch(this.selectData[0], 'ID_WAT_Terminate', 'getcanterminatebatch')
    },
    // 下载模板
    downTemplate() {
      // this.$refs.downTemplate.dialogVisible = true
      this.$downByBlob('', '工单全套模板.xls', 'a/workorder/workorder/downloadAllTemplate')
    },
    // 导出
    _export() {
      if (this.selectData.length <= 0) return
      let postData = this.selectData.reduce((pre, cur) => [...pre, cur.id], [])
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/workorder/workorderExcel/export',
        data: {
          workorderIds: postData.join(',')
        },
        noCommit: true
      }).then(res => {
        if (res.data.exportPath) {
          let url = res.data.exportPath
          let a = document.createElement('a')
          let evt = document.createEvent('HTMLEvents') // 对firefox的兼容
          evt.initEvent('click', false, false) // 对firefox的兼容
          a.style.display = 'none'
          a.href = url
          a.download = '工单导出数据.xlsx'
          a.dispatchEvent(evt) // 对firefox的兼容
          a.click()
          window.URL.revokeObjectURL(url)
        }
      })
    },
    // 获取批次
    getPausedBatch(workOrder, type, url) {
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnoverbatch/turnoverBatch/' + url,
        data: {
          workorderIds: [workOrder.id]
        },
        noCommit: true
      }).then(res => {
        this.$refs.WorkOrderBatch.openDialog({
          batchList: res.data,
          type: type
        })
      })
    },
    // 批次提交回调
    _submitBatch(obj) {
      let successMsg = ''
      let turnoverBatchActionId = ''
      switch (obj.type) {
        case 'ID_WAT_Pause':
          successMsg = '暂停成功！'
          turnoverBatchActionId = 'ID_BAT_Pause'
          break
        case 'ID_WAT_Resume':
          successMsg = '恢复成功！'
          turnoverBatchActionId = 'ID_BAT_Resume'
          break
        case 'ID_WAT_Terminate':
          successMsg = '终止成功！'
          turnoverBatchActionId = 'ID_BAT_Terminate'
          break
      }
      if (obj.data) {
        // 有选择批次
        this.changeStatus({
          workorderActionId: obj.type,
          isInputSemisStore: obj.isInputSemisStore,
          msg: successMsg,
          turnoverBatchActionId: turnoverBatchActionId,
          turnoverBatchIds: obj.data,
          reason: obj.reason,
        })
      } else {
        // 没选择批次
        this.changeStatus({
          workorderActionId: obj.type,
          isInputSemisStore: obj.isInputSemisStore,
          msg: successMsg,
          reason: obj.reason,
        })
      }
    },
    // 清理搜索条件
    clearSearch() {
      this.$refs.mesSearch.clean()
      this.$refs.mesTable.clearSort()
      this.$refs.mesTable.clearFilter()
      this.searchData = {}
      this.sortData = {}
      this.init()
    },
    // 刷新方法
    refresh() {
      this.taskNumber = ''
      this.workorderIds = []
      this.taskInfoDetail = {}
      this.$refs.taskBomTree.init()
      this.clearSearch()
    },
    // 任务号回调
    _selectNode(taskNumber, workorderIds) {
      this.taskNumber = taskNumber
      this.workorderIds = workorderIds
      this.getTaskInfo()
      this.clearSearch()
    },
    // 获取任务号信息
    getTaskInfo() {
      let params = {}
      this.taskInfoDetail = {}
      if (this.taskNumber) {
        params.taskNumber = this.taskNumber
      } else if (this.workorderIds.length) {
        params.workorderId = this.workorderIds[0]
      }
      this.$store.dispatch('saveData', {
        method: 'get',
        url: 'a/task/task/queryTask',
        params: params,
        noCommit: true
      }).then(res => {
        this.taskInfoDetail = res.data || {}
      })
    },
    // 格式化数据
    formatPostData(page) {
      let postData = {
        pageNo: page ? page.pageNo : 1,
        pageSize: page ? page.pageSize : this.listData.pageSize || 15,
        sort: this.sortData,
        query: {
          columns: this.tableColConfig.reduce((pre, cur) => [...pre, cur.prop], []),
          ...this.searchData,
          viewSource: 1, // viewSource 视图来源，1表示计划工单
        }
      }
      if (this.taskNumber) {
        postData.query.taskNumber = this.taskNumber
      }
      if (this.workorderIds.length) {
        postData.query.id = this.workorderIds.toString()
      }
      return postData
    },
    // 导出表格
    _exportTable() {
      let postData = this.formatPostData({
        pageNo: 1,
        pageSize: 9999999
      })
      this.$exportTable(postData, 'a/workorder/workorder/exportasexcel', this.titleText)
    },
    // 初始化
    init(page) {
      this.isLoading = true
      let postData = this.formatPostData(page)
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/workorder/workorder/list',
        data: postData,
        module: 'workListReceive',
        state: 'listData'
      }).then((res) => {
        if (Object.keys(this.searchData).length > 0) {
          this.searchResult = res.count
        } else {
          this.searchResult = NaN
        }
      }).finally(() => {
        this.isLoading = false
      })
    },
    // 显示导入弹框
    showImport() {
      this.$refs.importStep.openDialog()
    },
    // 显示日志
    showLog(row) {
      this.$refs.logDetail.openDialog({
        title: '工单编号',
        name: row.number,
        url: 'a/workorderstatuschangehistory/workorderStatusChangeHistory/list',
        query: {
          workorderId: row.id
        }
      })
    },
    // 只显示暂停，恢复的日志
    filterlog() {
      this.$refs.logDetail.openDialog({
        title: '工单编号',
        name: this.selectData[0].number,
        url: 'a/workorderstatuschangehistory/workorderStatusChangeHistory/filterlog',
        data: {
          workorderId: this.selectData[0].id
        }
      })
    },
    // 搜索
    _info(data) {
      this.searchData = data
      this.$refs.mesTable.clearFilter()
      this.$refs.mesTable.clearSort()
      this.sortData = {}
      this.init()
    },
    // 复选框
    handleSelectionChange(val) {
      this.selectData = val
    },
    // 排序
    _sort(obj) {
      this.sortData = this.$getSortOrder(obj)
      this.init()
    },
  }
}
</script>

<style lang="less" scoped>
  .work_list_receive {
    height: 100%;
    .task_info_cont{
      padding: 0px 20px 20px;
    }
    .down_btn {
      .see_history {
        text-decoration: none;
        color: @mesFontBlue;
        font-size: 14px;
        padding-left: 15px;
        padding-right: 10px;
        border-left: @mesBorDefault;
        &:hover {
          color: darken(@mesFontBlue, 5%);
        }
        &:active {
          color: darken(@mesFontBlue, 10%);
        }
      }
      .download_btn {
        color: @mesFontBlue;
        font-size: 14px;
        padding-right: 10px;
        cursor: pointer;
        &:hover {
          color: darken(@mesFontBlue, 5%);
        }
        &:active {
          color: darken(@mesFontBlue, 10%);
        }
      }
    }
    .jump_item .iconfont {
      font-size: 14px;
    }
  }
</style>
<style lang="less">
  .err_msg {
    .el-table__header-wrapper {
      display: none;
    }
    .el-table td {
      padding: 0;
      height: 30px;
      line-height: 30px;
    }
  }
</style>
